package com.runen.wnhz.runen.ui.activity.mine;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.aspectj.CheckNet;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetStateUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.MyCollection;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.di.component.DaggerMyCollectionComponent;
import com.runen.wnhz.runen.di.module.MyCollectionModule;
import com.runen.wnhz.runen.presenter.Contart.MyCollectionContract;
import com.runen.wnhz.runen.presenter.iPresenter.IMyCollectionPersenter;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.MyCollectionRecyclerAdapter;
import com.runen.wnhz.runen.ui.adapter.puadapter.MyOrderAdapter;
import com.runen.wnhz.runen.widget.TitleBuilder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018-04-12.
 */

public class MyCollectionActivity extends BaseActivity<IMyCollectionPersenter>
        implements MyCollectionContract.View, View.OnClickListener
        , BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.refresh_srl)
    SmartRefreshLayout refreshSrl;
    private RecyclerView mRecyclerView;
    private MyOrderAdapter mAdapter;

    private UserBean mUser;
    private int mPage = 0;
    private int currentPage = 0;
    private int totalPage = 0;
    private boolean hasNextPage = false;
    private List<MyCollection.DataBean.ListBean> listBeans;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;
    private MyCollectionRecyclerAdapter adapter;
    private String token;

    @Override
    protected int getLayoutView() {
        return R.layout.my_collection_activity_layout;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {
        switch (clicked) {
            case LEFT:
                finish();
                break;
        }
    }

    private void setListener() {
        refreshSrl.setEnableAutoLoadMore(false);
        refreshSrl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (NetStateUtils.isNetworkAvalible(MyCollectionActivity.this)) {
                    if (hasNextPage) {
                        isLoadMore = true;
                        int tempCurrentPage = currentPage + 1;
                        getMyCollectionData(String.valueOf(tempCurrentPage));
                    } else {
                        ToastUtil.showToast("没有更多数据");
                        refreshSrl.finishLoadMore(true);
                    }
                } else {
                    ToastUtil.showToast("当前暂无网络");
                    refreshSrl.finishLoadMore(false);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (NetStateUtils.isNetworkAvalible(MyCollectionActivity.this)) {
                    int tempCurrentPage = 0;
                    isRefresh = true;
                    getMyCollectionData(String.valueOf(tempCurrentPage));
                } else {
                    ToastUtil.showToast("当前暂无网络");
                    refreshSrl.finishRefresh(false);
                }
            }
        });
    }

    private void getMyCollectionData(String page) {
        if(token != null) {
            FormBody formBody = new FormBody.Builder().add("token",token).add("page", page).build();
            System.out.println("tttttttttoken == " + token);
            Request.Builder builder = new Request.Builder().url(NetUtils.Ucenter_userFavorite).post(formBody);
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(builder.build());
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                            if (isLoadMore) {
                                refreshSrl.finishLoadMore(false);
                                isLoadMore = false;
                            }
                            if (isRefresh) {
                                refreshSrl.finishRefresh(false);
                                isRefresh = false;
                            }
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                handleUserCollectionData(response);
                            } catch (IOException e) {
                                e.printStackTrace();
                                ToastUtil.showToast("数据请求异常");
                                if (isLoadMore) {
                                    refreshSrl.finishLoadMore(false);
                                    isLoadMore = false;
                                }
                                if (isRefresh) {
                                    refreshSrl.finishRefresh(false);
                                    isRefresh = false;
                                }
                            }
                        }
                    });
                }
            });
        }
    }

    private void handleUserCollectionData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                MyCollection myCollection = new Gson().fromJson(json, MyCollection.class);
                if ("1".equals(myCollection.getRe())) {
                    MyCollection.DataBean dataBean = myCollection.getData();
                    if (dataBean != null) {
                        if ("1".equals(dataBean.getIs_page())) {
                            hasNextPage = true;
                        } else {
                            hasNextPage = false;
                        }
                        totalPage = Integer.parseInt(dataBean.getSum_page());
                        currentPage = Integer.parseInt(dataBean.getPage());

                        if (isRefresh) {
                            if (dataBean.getList().size() != 0) {
                                currentPage = 0;
                            }
                            refreshSrl.finishRefresh(true);
                            if (listBeans.size() != 0) {
                                listBeans.clear();
                            }
                            listBeans.addAll(dataBean.getList());
                            if (adapter == null) {
                                adapter = new MyCollectionRecyclerAdapter(listBeans, MyCollectionActivity.this);
                                mRecyclerView.setAdapter(adapter);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                            isRefresh = false;
                            return;
                        }
                        if (isLoadMore) {
                            if (dataBean.getList().size() != 0) {
                                currentPage = currentPage + 1;
                            }
                            refreshSrl.finishLoadMore(true);
                            listBeans.addAll(dataBean.getList());
                            if (adapter == null) {
                                adapter = new MyCollectionRecyclerAdapter(listBeans, MyCollectionActivity.this);
                                mRecyclerView.setAdapter(adapter);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                            isLoadMore = false;
                            return;
                        }

                        listBeans.addAll(dataBean.getList());
                        adapter = new MyCollectionRecyclerAdapter(listBeans, MyCollectionActivity.this);
                        mRecyclerView.setAdapter(adapter);
                    }
                } else if ("0".equals(myCollection.getRe())) {
                    ToastUtil.showToast(myCollection.getInfo());
                    if (isLoadMore) {
                        refreshSrl.finishLoadMore(false);
                        isLoadMore = false;
                    }
                    if (isRefresh) {
                        refreshSrl.finishRefresh(false);
                        isRefresh = false;
                    }
                }
            }
        }
    }


    @Override
    protected void initStart() {
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        mUser = ACacheUtlis.getInstance().getReqeustUser(this);

        mRecyclerView = findViewById(R.id.list_rv);
        listBeans = new ArrayList<>();
        if(ACacheUtlis.getInstance().getReqeustUser(MyCollectionActivity.this) != null) {
            token = ACacheUtlis.getInstance().getReqeustUser(MyCollectionActivity.this).getToken();
        }


//        mAdapter = new MyOrderAdapter(mContext);
//        mAdapter.setOnLoadMoreListener(this);
//        mAdapter.setPreLoadNumber(5);
//        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        setListener();
        getMyCollectionData(String.valueOf(currentPage));
//        mRecyclerView.setAdapter(mAdapter);

//        getCollectionList();
    }

    @CheckNet
    public void getCollectionList() {
        mPresenter.getCollectionList();
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        mTitleBuilder.setMiddleTitleText("我的收藏")
                .setLeftDrawable(R.mipmap.icon_back)
                .seTitleBgRes(R.mipmap.bg_title)
                .setMiddleTitleTextColor(ContextCompat.getColor(this, R.color.text_white));
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {
        DaggerMyCollectionComponent.builder().applicationComponent(appComponent)
                .myCollectionModule(new MyCollectionModule(this))
                .build().inject(this);
    }


    @Override
    public void onClick(View v) {

    }

    @Override
    public String getPage() {
        return mPage + "";
    }

    @Override
    public String getToken() {
        return mUser.getToken();
    }

    @Override
    public void onSuccess(MyCollection.DataBean dataBean) {
        MyCollection.DataBean collection = dataBean;


    }

//    @Override
//    public void onSuccess(DataBean dataBean) {
//        mSwipeRefreshLayout.setRefreshing(false);
//    }


    @Override
    public void onLoadMoreRequested() {
        mRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                getCollectionList();
            }
        });
    }

    private void setData(boolean isRefresh, List data) {
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < 10) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
